package demo1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        int port = 5555;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器启动，监听端口 " + port);

            // 等待客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接：" + clientSocket.getInetAddress());

            // 输入输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            String inputLine;
            // 读取客户端发送的字符串
            while ((inputLine = in.readLine()) != null) {
                System.out.println("收到客户端消息: " + inputLine);

                // 判断是否退出
                if ("-1".equals(inputLine.trim())) {
                    out.println("Bye");
                    break;
                }

                // 转换成大写并返回
                String response = inputLine.toUpperCase();
                out.println(response);
                System.out.println("返回给客户端: " + response);
            }

            // 关闭连接
            in.close();
            out.close();
            clientSocket.close();
            System.out.println("客户端已断开");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
